"""Stock indicators."""

import logging
import datetime as dt
import numpy as np
import misc.quoteperiod as qp
import system.navalasystem as na
from misc import parts
from misc import timedata
from  misc import misc
from indicator import StockIndicator



class ManyStocksProcessor(parts.Stocker):
    ## Setup
    indicator = None
    
    def __init__(self):
        self.logger = misc.GetLogger("manystocksprocessor")
    
    def CalculateEverything(self):
        if misc.isempty(self.indicator.name):
            raise RuntimeError("Indicator does not have a name!")
        i, ii = 0, 0
        n = len(self._allNames)
        for name in self._allNames:
            print name, "..."
            Q = self.indicator.DoTheTimeDataShit(name)
            logging.debug("PPOORRQQUUEE O QQQQQ EH VAZIO??? %s`" % Q)
            na.vala.db.td_Record(self.indicator, name, Q)
            
            # TODO create signal for the progress indicator
            i += 1
            ii += 1
            if ii == 10:
                print "%d/%d (%.1g %%)" % (i, n, float(i)/n*100)
                ii = 0


################################################################################

class Min1QuoteCount(StockIndicator):
    """Counts quotes for 1-minute interval..."""
    ##Setup
    # =10. Number of days.
    numDays = 10
    
    _period = qp.daily
    
    def GetValue(self, name):
        dt2 = self.GetRefDt().replace(hour=23, minute=59)
        dt1 = misc.BeginningOfDay(dt2-dt.timedelta(days=self.numDays-1))
        Q = na.vala.store.GetQuotes(qp.min1, name, dt1, dt2)
        return len(Q)


class Volume(StockIndicator):
    """Volume from reference data."""
    
    _period = qp.daily
    
    def GetValue(self, name):
        d = self.GetRefDt()
        Q = na.vala.store.GetQuotes(self.GetPeriod(), name, misc.BeginningOfDay(d), d)
        if len(Q) == 0:
            return -1
        else:
            return Q.volume[-1]

    def FormatValue(self, value):
        return "%12d" % value

"EITCHAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
class Close(StockIndicator):
    """Close price from reference data."""
    
    _period = qp.daily
    
    def GetValue(self, name):
        d = self.GetRefDt()
        Q = na.vala.store.GetQuotes(self.GetPeriod(), name, misc.BeginningOfDay(d), d)
        if len(Q) == 0:
            return -1
        else:
            return Q.close[-1]
            
    def FormatValue(self, value):
        return "%7.2f" % value

class Volatility(StockIndicator):
    """Volatility as standard deviation as % of mean."""
    ##Setup
    # =20. Number of points.
    size = 20
    
    _period = qp.daily
    
    def GetValue(self, name):
        d = self.GetRefDt()
###        logging.debug("POOOOOOOOOOOOOOOOO %s %d" % (qp.data[self.GetPeriod()]["english"], self.size))
        Q = na.vala.store.GetQuotes(self.GetPeriod(), name,
            dt2=d, numPoints=self.size)
        if len(Q) == 0:
            return -1
        else:
#            v = misc.last_n(Q.close, self.numDays)
            v = Q.close
            return np.std(v)/np.mean(v)
        
    def FormatValue(self, value):
        return "%0.6f" % value





class VolatilityHourly(Volatility):
    size = 28
    _period = qp.hourly
